package com.intelligentmeterreadingsys.service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.intelligentmeterreadingsys.httpserver.HttpClientServer;
import com.intelligentmeterreadingsys.httpserver.RequestUrl;
import com.intelligentmeterreadingsys.httpserver.UploadHttpClient;
import com.intelligentmeterreadingsys.povo.WaterInfoVO;
import com.intelligentmeterreadingsys.util.FileNameUtil;
import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;
import com.intelligentmeterreadingsys.waterlist.reviewdata.db.ReviewDataDao;

import dbhelper.DbTableName;
import dbhelper.XmlNameHelper;

import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

/**
 * 检查前抄表员是否有 复查数据需要下载
 * @author king
 *
 */
public class ReviewDataDownloadService extends Service{

	public Timer myTimer=null;//定时器
	
	public TimerTask myTimerTask=null;//定时任务
	
	public HttpClientServer server=null;//HTTP服务
	
	public List<WaterInfoVO> list=null;//当前已抄复查数据
	
	public int count=0;//当前抄表的复查数据数
	
	public String uploadurl;
	
	public String downloadurl;
	
	public String imsi;
	
	
	@Override
	public IBinder onBind(Intent intent) {
		
		return null;
	}

	@Override
	public void onCreate() {
	    SharedPreferenceUtil sh=new SharedPreferenceUtil(this);
	     imsi=  sh.getValue(XmlNameHelper.IMSI);
	     RequestUrl r=new RequestUrl(this);
	     uploadurl=r.getUrl(RequestUrl.REVIEWUPLOAD);
	     downloadurl=r.getUrl(RequestUrl.REVIEWDOWNLOAD);
	     init();
	     start();
		super.onCreate();
	}
	
	/**
	 * 初始化
	 */
    public void init(){
    	server=new HttpClientServer(this);
    	myTimer=new Timer();
    	myTimerTask=new TimerTask() {
			
			@Override
			public void run() {
				System.out.println("启动服务。。。。。。。。。。。。。。。。");
				ReviewDataDao dao=new ReviewDataDao(ReviewDataDownloadService.this);
				count=dao.queryNoUpload();
				dao.close();
				if(count>0){
				 boolean b=	upload();
				 if(b){
					 delect();
					 download();
				 }
				}else{
					 delect();
					 download();
				}
				
				
			}
		};
    }

    /**
     * 打开定时器
     */
    public void start(){
    	   RequestUrl r=new RequestUrl(this);
    	 uploadurl=r.getUrl(RequestUrl.REVIEWUPLOAD);
	     downloadurl=r.getUrl(RequestUrl.REVIEWDOWNLOAD);
    	if(myTimer!=null){
    		myTimer.schedule(myTimerTask, 1000, 30000);
    	}
    }
    
    Handler myHandler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			
		}
    	
    };
    
    /**
     * 上传
     * @return
     */
    public boolean upload(){
    	
    	ReviewDataDao dao=new ReviewDataDao(this);
    	List<WaterInfoVO> list=dao.queryAllNoUpload(null);

		for(int i=0;i<list.size();i++){
			
			Map<String, String> map3=new HashMap<String, String>();
			Map<String, String> map2=new HashMap<String, String>();
			Map<File, String> map1=new HashMap<File, String>();
			WaterInfoVO waterinfo=list.get(i);
			
			map3.put("waternumber", waterinfo.getWaternumber());
			map3.put("thismonthwater" + "", waterinfo.getThismonthwater()+"");		
			String usewater=(waterinfo.getThismonthwater()-waterinfo.getLastmonthwater())+"";		
			map3.put("usewater", usewater);
			map3.put("thisdate", waterinfo.getThisdate());
			map3.put("imsi",imsi);
			map3.put("desc", waterinfo.getDesc());
			map3.put("sid", waterinfo.getSid());
			List<String> lists=waterinfo.getImagepath();
			for(int k=0;k<lists.size();k++){
				File file=new File(lists.get(i));
				if(file.exists()){				
					map2.put(file.getName(), "imagename");
					map1.put(file, "imagepath");
				}							
			}	
			
			String respon=	UploadHttpClient.uploadSubmit(uploadurl, map2, map1,map3);
			if(respon.equals("error")){
				
				return false;
			}else{
				try {
					JSONObject json=new JSONObject(respon);
					String message=json.getString("message");
					if(message.equals("yes")){
						
					}else{
						
						return false;
					}
				} catch (JSONException e) {
					
					return false;
				}
				
			}
		}    	
		return true;    	
    }

    
    /**
     * 下载复查数据
     * @return
     */
    public boolean download(){		 
		  Map<String, String> map=new HashMap<String, String>();
		  map.put("imsi", imsi);
		   String response=  server.doPost(map, RequestUrl.REVIEWDOWNLOAD);
		   System.out.println(response);
		   if(!response.equals("error")){
			   try {
				JSONObject obj=new JSONObject(response);
				//水表信息
				JSONArray waterinfo=obj.getJSONArray("waterinfo");
				System.out.println(waterinfo.toString());
				int a=waterinfo.length();
//				//表册信息
//				JSONArray waterlist=obj.getJSONArray("waterlist");
//				int b=waterlist.length();
				//用户信息
				JSONArray userinfo=obj.getJSONArray("userinfo");
				int c=userinfo.length();
				//月用水量信息
				JSONArray usewater=obj.getJSONArray("usewaterinfo");
				//工程单类型
				JSONArray ordertype=obj.getJSONArray("typeinfo");
				
	           		
				List<ContentValues> listwaterinfo=new ArrayList<ContentValues>();
				for(int i=0;i<waterinfo.length();i++){
					JSONObject jb=waterinfo.getJSONObject(i);
					ContentValues value=new ContentValues();
					value.put("waternumber", jb.getString("waternumber"));
					value.put("waterlistid", jb.getString("waterlistid"));
					value.put("usernumber", jb.getString("usernumber"));
					value.put("wateradds", jb.getString("wateradds"));
					if(jb.getString("alarmlimit").equals("null")){
						value.put("alarmlimit", 0.0);
					}else{
						value.put("alarmlimit", jb.getDouble("alarmlimit"));
					}
				
					if(jb.getString("lowalarmlimit").equals("null")){
						value.put("lowalarmlimit", 0.0);
					}else{
						value.put("lowalarmlimit", jb.getDouble("lowalarmlimit"));
					}
					if(!jb.getString("RFIDnumber").equals("null")){
						value.put("RFIDnumber", jb.getString("RFIDnumber"));
					}
					String latitude=jb.getString("latitude");
					if(!latitude.equals("null")){
						value.put("latitude", jb.getDouble("latitude"));
					}
					String longitude=jb.getString("longitude");
					if(!longitude.equals("null")){
						value.put("longitude", jb.getDouble("longitude"));
					}
					String lastmonthwater=jb.getString("lastmonthwater");
					if(!lastmonthwater.equals("null")){
						value.put("lastmonthwater", jb.getDouble("lastmonthwater"));
					}else{
						value.put("lastmonthwater", 0.0);
					}
					
					String rfidnumber=jb.getString("RFIDnumber");
					if(!rfidnumber.equals("null")){
						value.put("RFIDnumber", jb.getString("RFIDnumber"));
					}
					if(rfidnumber.equals("null")&&latitude.equals("null")){
						value.put("bandingstatus", "3");
					}
					if(!rfidnumber.equals("null")&&!latitude.equals("null")){
						value.put("bandingstatus", "2");
					}
					if(!rfidnumber.equals("null")&&latitude.equals("null")){
						value.put("bandingstatus", "4");
					}
					value.put("metercaliber", jb.getString("metercaliber"));
					value.put("lastdate", jb.getString("lastdate"));
					value.put("iscopystatus", "未复抄");
					value.put("isupload", "0");	
					value.put("sid", jb.getString("sid"));
					value.put("ismultiplecopy", "1");
					value.put("waterproperties", jb.getString("waterproperties"));
					
					listwaterinfo.add(value);
				}
				
				List<ContentValues> listuserinfo=new ArrayList<ContentValues>();
				for(int i=0;i<userinfo.length();i++){
					JSONObject jb=userinfo.getJSONObject(i);
					ContentValues value=new ContentValues();
					value.put("username", jb.getString("name"));
					value.put("usernumber", jb.getString("number"));
					value.put("phone", jb.getString("phone"));
					value.put("useradds", jb.getString("adds"));
					value.put("usertype", jb.getString("usertype"));
					value.put("userstatus", jb.getString("status"));
					value.put("ismultiplecopy", "1");
					listuserinfo.add(value);
					
				}
				
				List<ContentValues> listusewater=new ArrayList<ContentValues>();
				for(int i=0;i<usewater.length();i++){
					JSONObject js=usewater.getJSONObject(i);
					 ContentValues value=new ContentValues();
					 value.put("waternumber",js.getString("waternumber") );
					 value.put("month", js.getString("month"));
					 if(js.getString("watercount").equals("null")){
						 value.put("watercount",0);
					 }else{
						 value.put("watercount", js.getString("watercount"));
					 }
					 value.put("ismultiplecopy", "1");
					 listusewater.add(value);
					
				}
				
//				List<ContentValues> listwaterlist=new ArrayList<ContentValues>();
//				for(int i=0;i<waterlist.length();i++){
//					JSONObject js=waterlist.getJSONObject(i);
//					ContentValues value=new ContentValues();
//					value.put("number", js.getString("number"));
//					value.put("watercount", js.getString("watercount"));
//					value.put("date", DateUtil.getBeforeDay(0));
//				
//					listwaterlist.add(value);
//					publishProgress(a+b+c+i);
//					
//				}
			
				List<ContentValues> listordertype=new ArrayList<ContentValues>();
				for(int i=0;i<ordertype.length();i++){
					JSONObject json=ordertype.getJSONObject(i);
					ContentValues value=new ContentValues();
					value.put("name", json.getString("name"));
					value.put("number", json.getString("number"));
					value.put("status", "2");
					listordertype.add(value);
				}
				ReviewDataDao dao=new ReviewDataDao(ReviewDataDownloadService.this);
				dao.insertALL(listordertype, DbTableName.TYPE);
				boolean b1=true;
				//b1=dao.insertALL(listwaterlist, DbTableName.WATERLIST);
				if(b1){
					b1=dao.insertALL(listuserinfo, DbTableName.USERINFO);
					if(b1){
						b1=dao.insertALL(listusewater, DbTableName.USEWATERINFO);
						if(b1){
							b1=dao.insertALL(listwaterinfo, DbTableName.WATERINFO);
						}
					}
				}
				
				dao.close();
				if(b1){
				   return false;
				}else{
				   return true;
				}
			} catch (JSONException e) {
			
				return false;
				
			}
			   
		   }
		return true;
		  
    	
    };
    
    /**
     * 删除数据
     */
    public void delect(){
    	ReviewDataDao dao=new ReviewDataDao(this);
    	dao.delectReivew();
    	dao.close();
    	FileNameUtil file=new FileNameUtil(this);
    	file.delectFile("ReviewImage");
    }

	@Override
	public void onDestroy() {
	    if(myTimer!=null){
	    	myTimerTask.cancel();
			myTimer.cancel();
	    }
		super.onDestroy();
	}
    
    
}
